layui.use(['form', 'upload'], function () {
    var $ = layui.jquery;
    var form = layui.form,
        layer = layui.layer,
        layuimini = layui.layuimini,
        upload = layui.upload;

    /**
     * 初始化表单，要加上，不然刷新部分组件可能会不加载
     */
    form.render();

    //初始化
    $(function(){
        var index = layer.load(2);
        var url = "/web/webIndex/getLoginUser";
        $.post(url, {}, function(data){
            layer.close(index);
            if(data.state == '200'){
                $("#head_image").attr("src", "/head_photo/" + data['loginUser'].headPhoto);
                $("#set_userName").val(data['loginUser'].userName);
                $("#set_nickName").val(data['loginUser'].nickName);
                for(var i = 0; i < $("input[name='sex']").length; i++){
                    if($($("input[name='sex']")[i]).val() == data['loginUser'].sex){
                        $($("input[name='sex']")[i]).attr("checked", "checked");
                        break;
                    }
                }
                for(var i = 0; i < $("input[name='status']").length; i++){
                    if($($("input[name='status']")[i]).val() == data['loginUser'].status){
                        $($("input[name='status']")[i]).attr("checked", "checked");
                        break;
                    }
                }
            }else {
                layer.msg(data.message, {icon:5})
            }
            form.render();
        })
    });

    //头像上传
    var uploadInst = upload.render({
        elem: '#headPhoto'
        ,url: '/sys/user/uploadHeadPhoto' //改成您自己的上传接口
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $('#head_image').attr('src', result); //图片链接（base64）
            });
        }
        ,done: function(res){
            //上传成功
            if(res.state == "200"){
                return layer.msg(res.message, {icon:1});
                //如果上传失败
            }else{
                return layer.msg(res.message, {icon:2});
            }
        }
        ,error: function(){
            //演示失败状态，并实现重传
            var demoText = $('#head_image_text');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs head-reload">重试</a>');
            demoText.find('.head-reload').on('click', function(){
                uploadInst.upload();
            });
        }
    });

    // 进行修改操作
    form.on('submit(saveBtn)', function (data) {
        data = data.field;

        var index = layer.load(2);
        var url = "/sys/user/save";
        $.post(url, data, function(res){
            layer.close(index);
            if(res.state == "200"){
                layer.msg(res.message, {icon: 1});
                layuimini.refresh();
            }else{
                layer.msg(res.message, {icon: 2});
            }
        });
        return false;
    });
});